package com.onekbase.demo.tcp;

import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Iterator;
public class TcpServerNioSelectorDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress("localhost", 8084));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            selector.select();
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = socketChannel.read(buffer);
                    if (bytesRead > 0) {
                        buffer.flip();
                        byte[] data = new byte[buffer.remaining()];
                        buffer.get(data);
                        String receivedData = new String(data);
                        System.out.println("Received: " + receivedData);
                        socketChannel.register(selector, SelectionKey.OP_WRITE);
                    }
                } else if (key.isWritable()){

                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    String response = "response data from server client";
                    ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());
                    socketChannel.write(responseBuffer);
                    socketChannel.close();
                }
                keyIterator.remove();
            }
        }
    }
}